package com.it.msmservice.controller;

import com.it.commonutils.R;
import com.it.msmservice.service.MsmService;
import com.it.msmservice.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/edumsm//msm")
@CrossOrigin
public class MsmController {
    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate <String,String>redisTemplate;

    //发送短信
    @GetMapping("send/{phone}")
    public R sendMsm(@PathVariable String phone){
        //从redis中获取验证码 获取直接返回
        String code = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code)){
            return R.ok();
        }
        //生成四位随机数
        code = RandomUtil.getFourBitRandom();
        Map<String,Object> param=new HashMap<String,Object>();
        param.put("code",code);
        //调用service发送短信方法
        boolean isSend=msmService.send(param,phone);
        if(isSend){
            //发送成功，把成功的验证码放到redis
            //设置有效时长5分钟
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
           return R.ok();
        }else{
            return R.error().message("短信发送失败");
        }
    }
}
